<?php

namespace app\api\service\order;
use app\api\model\UserCoupon as UserCouponModel;
use app\common\library\MysicLog;
use app\common\model\user\BalanceLog;
use app\common\model\user\PointsLog;
use app\common\model\user\PointsLog as PointsLogModel;
use app\factory\MqFactory;
use app\common\model\Wxapp as WxappModel;
use org\RabbitMQ;
use org\Redis;
use think\Hook;
use think\Db;
use app\api\service\Basics;
use app\api\model\User as UserModel;
use app\api\model\Order as OrderModel;
use app\api\model\user\MoneyLog as MoneyLogModel;
use app\common\enum\user\moneylog\Scene;
use app\common\service\goods\source\Factory as StockFactory;
use app\common\enum\OrderType as OrderTypeEnum;
use app\common\enum\order\PayType as PayTypeEnum;
use app\common\model\SingleOrder as SingleOrderModel;
use app\api\model\dealer\Referee as RefereeModel;

/**
 * 订单支付成功服务类
 * Class PaySuccess
 * @package app\api\service\order
 */
class PaySuccess extends Basics
{
    // 订单模型
    public $model;

    // 当前用户信息
    protected $user;
    //当前用户收益信息
    protected $userDeal;

    protected $mysicLog;

    /**onPaySuccess

     * 构造函数
     * PaySuccess constructor.
     * @param $orderNo
     * @throws \think\exception\DbException
     */
    public function __construct($orderNo)
    {
        // 实例化订单模型
        $this->model = OrderModel::getPayDetail($orderNo);
        if (!empty($this->model)) {
            $this->wxappId = $this->model['wxapp_id'];
        }
        // 获取用户信息
        $this->user = UserModel::detail($this->model['user_id']);
        $this->userDeal =$this->getUserDealer($this->model['user_id']);
        $this->mysicLog = MysicLog::instance();

    }
    private function getUserDealer($userId){
        return db('dealer_user')->where('user_id',$userId)->find();
    }
    protected function log($pre,$data = null)
    {
        $fileName = 'fenhong-queue'.date('Ymd', time()).'.log';
        if(!file_exists($fileName)) {
            if($data) {
                $data = is_array($data) ? json_encode($data, JSON_UNESCAPED_UNICODE) : $data;
                file_put_contents($fileName,  $pre . $data .  PHP_EOL, FILE_APPEND);
            } else {
                file_put_contents($fileName,  $pre .  PHP_EOL, FILE_APPEND);
            }
            chmod($fileName, 0766);
        }else {
            if($data) {
                $data = is_array($data) ? json_encode($data, JSON_UNESCAPED_UNICODE) : $data;
                file_put_contents($fileName,  $pre . $data .  PHP_EOL, FILE_APPEND);
            } else {
                file_put_contents($fileName,  $pre .  PHP_EOL, FILE_APPEND);
            }
        }

    }

    /**
     * 获取订单详情
     * @return OrderModel|null
     */
    public function getOrderInfo()
    {
        return $this->model;
    }

    /**
     * 订单支付成功业务处理
     * @param $payType 10 余额支付 20 微信支付
     * @param array $payData
     * @return bool
     */
    public function onPaySuccess($payType, $payData = [])
    {
        $this->mysicLog->setFilename('notify/order');
        if (empty($this->model)) {
            $this->error = '未找到该订单信息';
            $this->mysicLog->info($payType, '支付类型');
            $this->mysicLog->info(json_encode($payData), '支付数据');
//            $this->log('未找到订单信息: ' . '类型 - ' . $payType, json_encode($payData));
            return false;
        }

        $this->mysicLog->info([
            '订单ID' => $this->model->order_id, '用户id'=>$this->model->user_id, '订单编号' => $this->model->order_no,'商品总金额(不含优惠折扣)' => $this->model->total_price,
            '订单金额(含优惠折扣)' => $this->model->order_price, '实际付款金额(包含运费)' => $this->model->pay_price, '后台修改的订单金额（差价）' =>  $this->model->pay_price,
            '支付方式(10余额支付 20微信支付)' => $this->model->pay_type['value'], '付款状态(10未付款 20已付款)' => $this->model->pay_status['value'],'付款时间' =>$this->model->pay_time,
            '订单状态(10进行中 20取消 21待取消 30已完成)'=>$this->model->order_status['value'], '订单来源(10普通订单 20砍价订单 30秒杀订单 40购买会员订单 50当面付订单)' => $this->model->order_source,
            '是否为虚拟物品(1是 2不是)' => $this->model->is_fictitious,'分红与否(0未分红 1已份红)'=>$this->model->is_abouns
        ], '订单信息');

        // 更新付款状态
        $this->mysicLog->info('', '开始更新订单状态');
        $status = $this->updatePayStatus($payType, $payData);
        $this->mysicLog->info(bool2str($status), '更新订单状态是否成功');
        $order = db('order')->where('order_no',$this->model->order_no)->find();
        $this->mysicLog->info($order, '更新后的订单信息');
        // 订单支付成功行为
        if ($status == true) {
            $this->mysicLog->info('', '订单支付状态更新成功，准备入队列');
            $this->mysicLog->info('开始', '执行hook');
            try {
                Hook::listen('order_pay_success', $this->model, OrderTypeEnum::MASTER);
            } catch(\Exception $e) {
                $this->mysicLog->error(exceptionLogFormat($e), '订单支付成功调用Hook抛出异常');
            }
            $this->mysicLog->info('开始', '判断是否满足入队列条件');
            $this->mysicLog->info(bool2str($this->model['pay_type']['value'] == 20), '支付类型是否是微信支付');
            $this->mysicLog->info(bool2str(bcmul($this->model['pay_price'], '100') >= 1), '支付金额是否大于1分钱');
            $this->mysicLog->info(bool2str($this->model['is_fictitious'] == 1), '订单是否为虚拟物品');
            $this->mysicLog->info(bool2str(!empty($order['transaction_id'])), '订单transaction_id是否不为空');
            $this->mysicLog->info($this->model['coupon_id'], '优惠券ID');
            $this->mysicLog->info($this->model['balance_money'], '零钱抵扣');
            $this->mysicLog->info($this->model['points_money'], '积分抵扣');
            $setting=db('wxapp_setting')->where('wxapp_id',$this->model['wxapp_id'])->find();
            if($this->model['pay_type']['value'] == 20 && bcmul($this->model['pay_price'], '100') >= 1 && ($this->model['is_fictitious'] == 1 || $setting['real_reward'] == 1) ){
//                if(!empty($order['transaction_id'])) {
//                    //订单支付时间
//                    $rem = MqFactory::instance();
//                    $data=['orderId'=> $this->model['order_id'],'time'=>time()];
//                    $this->mysicLog->info($data, '成功订单入队列');
//                    $rem->send($data,'userListData','userListDataLog','userListDataLog');
//                }
                if(!empty($order['transaction_id'])) {
                    //如果使用了零钱或优惠券，实际支付的金额大于设置的最低金额，则本次订单不分红，但有分红资格。写入分红队列
                    if ($this->model['coupon_id']>0 || $this->model['balance_money']>0 || $this->model['points_money']>0){
                        if ($this->model['pay_price']>=$setting['money'] && $this->model['pay_time']>$setting['start_time']){
                            //订单支付时间
                            $rem = MqFactory::instance();
                            $data=['orderId'=> $this->model['order_id']];
                            $this->mysicLog->info($data, '成功订单入队列-使用优惠券或零钱，有分红资格，不分红');
                            $rem->send($data,'dividendBonus','dividendBonusLog','dividendBonusLog');
                        }

                    }else{
                        $wxApp = db('wxapp')->where('wxapp_id', $this->model['wxapp_id'])->find();
                        //订单支付时间
                        $rem = MqFactory::instance();
                        if(2 == $wxApp['service_type']) {
                            $data=['orderNo'=> $this->model['order_no'],'time'=>time()];
                            $this->mysicLog->info($data, '成功订单入队列-微股客');
                            $rem->send($data,'new-share','refund','refund');
                        } else {
                            $data=['orderId'=> $this->model['order_id'],'time'=>time()];
                            $this->mysicLog->info($data, '成功订单入队列-龙达');
                            $rem->send($data,'userListData','userListDataLog','userListDataLog');
                        }
                    }
                }
            }

        }
        return $status;
    }

    /**
     * 更新付款状态
     * @param $payType
     * @param array $payData
     * @return bool
     */
    private function updatePayStatus($payType, $payData = [])
    {

        // 验证余额支付时用户余额是否满足
        if ($payType == PayTypeEnum::BALANCE) {
            if ($this->user['money'] < $this->model['pay_price']) {
                $this->mysicLog->error(['用户余额' => $this->user['money'], '支付金额' => $this->model['pay_price']],'用户余额不足，无法使用余额支付');
                return false;
            }
        }
        $result = false;
        try{
//            $this->model->transaction(function () use ($payType, $payData) { //此处不用事务，避免其他入库操作失败导致订单更新失败
            if($this->model['order_source']==50) {
                $result = $this->updateFaceOrderInfo($payType, $payData);
            } elseif($this->model['order_source']==10) {
                $result = $this->updateOrderInfo($payType, $this->model,$payData);
            }elseif ($this->model['order_source']==20){
                $result = $this->updateOrderInfo($payType, $this->model,$payData);
            }elseif ($this->model['order_source']==30){
                $result = $this->updateOrderInfo($payType, $this->model,$payData);
            }

            // +----------------------------------------------------------------------
            // | 用户总支付的金额、充值余额、用户可用积分变更---user
            // +----------------------------------------------------------------------
            Db::name('user')->where(['user_id'=>$this->user['user_id']])->setInc('pay_money',$this->model['pay_price']);
            $this->mysicLog->info("成功", '用户总支付的金额变更');

            // +----------------------------------------------------------------------
            // | 用户单条订单记录表加数据---single_order
            // +----------------------------------------------------------------------
            $orderData['amount'] = $this->model['pay_price'];
            $orderData['pay_type'] = $payType;
            $orderData['wxapp_id'] = $this->model['wxapp_id'];
            $orderData['user_id'] = $this->model['user_id'];
            $this->singleOrder(['wxapp_id'=>$this->model['wxapp_id'],'user_id'=>$this->user['user_id']],$orderData);
            $this->mysicLog->info("成功", '用户单条订单记录表加数据成功');

            // +----------------------------------------------------------------------
            // | 判断用户是否有上级，有则进行分销处理
            // +----------------------------------------------------------------------
            $upuserId = RefereeModel::isExistReferee($this->model['user_id']);

            $this->mysicLog->info($upuserId, '用户上级ID');

            $upuserInfo = UserModel::detail($upuserId);
            if($upuserInfo){
                $userData = [
                    'user_id'=>$upuserInfo['user_id'],
                    'nickName'=>$upuserInfo['nickName'],
                    'pay_money'=>$upuserInfo['pay_money'],
                    'shareholder'=>$upuserInfo['shareholder'],
                    'vip_level'=>$upuserInfo['vip_level'],
                    'is_staff'=>$upuserInfo['is_staff'],
                    'deacler'=>$upuserInfo['deacler'],
                ];
                $this->mysicLog->info($userData, '上级详情');
            }

            // +----------------------------------------------------------------------
            // | 获取上级用户的单笔支付金额
            // +----------------------------------------------------------------------
            $amount = Db::name("single_order")
                ->where(['wxapp_id'=>$this->model['wxapp_id'],'user_id'=>$upuserId])
                ->value('amount');
            $this->mysicLog->info($amount, '获取上级用户的总支付金额');


            // +----------------------------------------------------------------------
            // | 查看商户设置的分销方案
            // +----------------------------------------------------------------------
            $dealer_case = WxappModel::dealerCase($this->model['wxapp_id']);
            $this->mysicLog->info($dealer_case, '获取分销方案');


            // +----------------------------------------------------------------------
            // | 获取当前分销方案一的配置
            // +----------------------------------------------------------------------
            $dealer_setting_one = Db::name("distribution_setting")
                ->where(['wxapp_id'=>$this->model['wxapp_id'],'dealer_type'=>1])
                ->value('setting_content');
            $this->mysicLog->info($dealer_setting_one, '获取当前分销方案一的配置');

            // +----------------------------------------------------------------------
            // | 获取当前分销方案二的配置
            // +----------------------------------------------------------------------
            $dealer_setting_tow = Db::name("distribution_setting")
                ->where(['wxapp_id'=>$this->model['wxapp_id'],'dealer_type'=>2])
                ->value('setting_content');
            $this->mysicLog->info($dealer_setting_tow, '获取当前分销方案二的配置');

            $checkDealeModel = new UserModel;

            // +----------------------------------------------------------------------
            // | 当面付订单
            // +----------------------------------------------------------------------
            if($this->model['order_source']==50 ){

                $this->mysicLog->info('开始', '当面付订单分销');

                if($this->model['pay_type']['value']==20){

                    if ($upuserId) {

                        if ($dealer_case == 1) {
                            $checkDealer = $checkDealeModel->getConfigByUserType($upuserInfo, $type = "face");
                            if ($checkDealer) {
                                $this->mysicLog->info($checkDealer, '获取分销方案1配置');
                                if ($checkDealer['consume_charge'] > 0) {
                                    //创建分销订单
                                    $this->createFaceOrder($this->model, $checkDealer['consume_charge'], $upuserId, $upuserInfo['wxapp_id'], 50, 10, $dealer_case);
                                }
                            }
                        } elseif ($dealer_case = 2) {
                            $checkDealer = $checkDealeModel->getDealerTow($upuserInfo, $type = "face_status");
                            $this->mysicLog->info($checkDealer, '获取分销方案2配置');
                            if ($checkDealer) {
                                $this->createFaceOrder($this->model, $checkDealer, $upuserId, $upuserInfo['wxapp_id'], 50, 10, $dealer_case);
                            }
                        }
                    }

                }
            }elseif($this->model['order_source']==10){

                $this->mysicLog->info('开始', '商品支付分销');

                if($this->model['pay_type']['value']==20){

                    if ($upuserId) {

                        if ($dealer_case == 1) {
                            $checkDealer = $checkDealeModel->getConfigByUserType($upuserInfo, $type = "goods");
                            $this->mysicLog->info($checkDealer, '获取分销方案1配置');
                            if ($checkDealer) {
                                //创建分销订单
                                $this->commonOrderOne($this->model,$checkDealer['consume_charge'],$upuserId,$upuserInfo['wxapp_id'],10,50,$dealer_case);

                            }
                        } elseif ($dealer_case = 2) {
                            $checkDealer = $checkDealeModel->getDealerTow($upuserInfo, $type = "product_status");

                            $this->mysicLog->info($checkDealer, '获取分销方案2配置');
                            if ($checkDealer) {

                                $this->commonOrderTwo($this->model,$checkDealer,$upuserId,$upuserInfo['wxapp_id'],10,50,$dealer_case);
                            }
                        }
                    }

                }

            }
            // 记录订单支付信息
            $this->updatePayInfo($payType);
//            });
        } catch(\Exception $e) {
            $result = false;
            $this->mysicLog->error(exceptionLogFormat($e), '更新订单状态抛异常');
        }
        $this->mysicLog->info(bool2str($result), '订单状态更新结果');
        return $result;
    }


    /**
     * 用户单条订单记录表
     * @param int $payType 支付类型
     * @param array $payData 支付回调数据
     * @return bool
     */

    public  function singleOrder($where,$data){
        //分销商表
        $flag = Db::name('single_order')->where($where)->find();
        if(!$flag){
            $single_data = [
                'amount'=>$data['amount'],
                'wxapp_id'=>$data['wxapp_id'],
                'pay_type'=>$data['pay_type'],
                'user_id'=>$data['user_id'],
                'create_time'=>time(),
                'update_time'=>time(),
            ];
            Db::name('single_order')->insertGetId($single_data);
        }else{
            if($flag['amount']<$data['amount']){
                $data['update_time'] = time();
                Db::name('single_order')->where($where)->update($data);
            }
        }
    }


    /**
     * 普通订单分销订单处理--分销方案一
     * @param int $payType 支付类型
     * @param array $payData 支付回调数据
     * @return bool
     */
    private function commonOrderOne($order,$consume_charge,$upUserId,$wxapp_id,$order_type,$flow_type,$dealer_case){

        $this->mysicLog->info("开始", '普通订单分销开始分销方案一');
        $this->mysicLog->info($consume_charge, '分销比例');
        $this->mysicLog->info($upUserId, '上级id');

        //计算分销佣金
        $capital = $this->getCapitalOne($order);


        $first_money = bcsub($capital['first_money'], 0, 2);
        $this->mysicLog->info($first_money, '分销金额');

        // +----------------------------------------------------------------------
        // | dealer_order表加数据----分销商订单记录表
        // +----------------------------------------------------------------------

        if($first_money>0){
            $data = [
                'user_id' => $order['user_id'],//用户id (买家)
                'order_id' => $order['order_id'],//订单id
                'order_type' => $order_type,//订单类型(10商城订单 20拼团订单 30 购买vip 40 购买爆品礼 50 当面付 60分红转化)
                'order_price' => $order['pay_price'],//订单支付金额
                'first_user_id' => $upUserId,//分销商用户id(一级)
                'second_user_id' => 0,//分销商用户id(二级)
                'third_user_id' => 0,//分销商用户id(三级)
                'first_money' => $first_money,//分销佣金(一级)
                'second_money' => 0,//分销佣金(二级)
                'third_money' => 0,//分销佣金(三级)
                'is_invalid' => 0,//订单是否失效(0未失效 1已失效)
                'is_settled' => 0,//是否已结算佣金(0未结算 1已结算)
                'wxapp_id' => $wxapp_id,//小程序id
                'create_time' => time(),//创建时间
                'update_time' => time(),//更新时间
                'dealer_case' => $dealer_case,//分销方案
            ];

            $this->mysicLog->info($data, '分销订单表dealer_order表加数据');
            $dealer_id = Db::name('dealer_order')->insertGetId($data);
            $this->mysicLog->info($dealer_id, '分销订单表dealer_order表加数据结果');


        }

        // 订单是否已完成
        if ($order['order_status']['value'] != 30) {
            $this->mysicLog->info($order['order_status']['value'], '订单状态为未完成，不满足分销条件');
            return false;
        }

        // 订单支付方式
        if ($order['pay_type']['value'] != 20) {
            return false;
        }

        // 分销订单详情
        $dealerOrder = Db::name('dealer_order')->where(['order_id'=>$order['order_id'],'is_settled'=>0,'order_type'=>$order_type])->find();

        if(!$dealerOrder){
            $this->mysicLog->info('', '无分销订单');
            return false;
        }
        $this->mysicLog->info($dealerOrder, '普通分销订单佣金分销订单详情');

        // +----------------------------------------------------------------------
        // | dealer_order表更新数据----分销商订单记录表
        // +----------------------------------------------------------------------
        Db::name('dealer_order')
            ->where(['order_id'=>$order['order_id'],'order_type'=>$order_type])
            ->update(['is_settled' => 1,'settle_time' => time()]);

        $this->mysicLog->info($dealerOrder['first_money'], '分销商用户记录表dealer_user，分销佣金');
        $this->mysicLog->info($dealerOrder['first_user_id'], '分销商用户记录表dealer_user，上级id');

        if($dealerOrder['first_user_id']>0 && $dealerOrder['first_money']>0){
            // +----------------------------------------------------------------------
            // | dealer_user表更新数据----分销商用户记录表
            // +----------------------------------------------------------------------
            Db::name('dealer_user')
                ->where(['user_id'=>$dealerOrder['first_user_id']])
                ->setInc('money', $dealerOrder['first_money']);


            // +----------------------------------------------------------------------
            // | dealer_capital表加数据----分销商资金明细表
            // +----------------------------------------------------------------------
            $capitalData = [
                'user_id'=>$dealerOrder['first_user_id'],
                'flow_type'=>$flow_type,
                'money'=>$dealerOrder['first_money'],
                'wxapp_id'=>$dealerOrder['wxapp_id'],
                'create_time'=>time(),
                'update_time'=>time(),
            ];

            $this->mysicLog->info($capitalData, '分销商资金明细表数据');
            $dealer_capital_id = Db::name('dealer_capital')->insertGetId($capitalData);

            $this->mysicLog->info($dealer_capital_id, '获取分销商资金明细表ID');
        }

    }



    /**
     * 普通订单分销订单处理--分销方案二
     * @param int $payType 支付类型
     * @param array $payData 支付回调数据
     * @return bool
     */
    private function commonOrderTwo($order,$consume_charge,$upUserId,$wxapp_id,$order_type,$flow_type,$dealer_case){


        $this->mysicLog->info("开始", '普通订单分销开始分销方案二');
        $this->mysicLog->info($consume_charge, '分销比例');
        $this->mysicLog->info($upUserId, '上级id');

        //计算分销佣金
        $first_money = bcmul($consume_charge/100, $order['pay_price'],2);
        $this->mysicLog->info($first_money, '分销金额');

        // +----------------------------------------------------------------------
        // | dealer_order表加数据----分销商订单记录表
        // +----------------------------------------------------------------------

        if($first_money>0){
            $data = [
                'user_id' => $order['user_id'],//用户id (买家)
                'order_id' => $order['order_id'],//订单id
                'order_type' => $order_type,//订单类型(10商城订单 20拼团订单 30 购买vip 40 购买爆品礼 50 当面付 60分红转化)
                'order_price' => $order['pay_price'],//订单支付金额
                'first_user_id' => $upUserId,//分销商用户id(一级)
                'second_user_id' => 0,//分销商用户id(二级)
                'third_user_id' => 0,//分销商用户id(三级)
                'first_money' => $first_money,//分销佣金(一级)
                'second_money' => 0,//分销佣金(二级)
                'third_money' => 0,//分销佣金(三级)
                'is_invalid' => 0,//订单是否失效(0未失效 1已失效)
                'is_settled' => 0,//是否已结算佣金(0未结算 1已结算)
                'wxapp_id' => $wxapp_id,//小程序id
                'create_time' => time(),//创建时间
                'update_time' => time(),//更新时间
                'dealer_case' => $dealer_case,//分销方案
            ];

            $this->mysicLog->info($data, '分销订单表dealer_order表加数据');
            $dealer_id = Db::name('dealer_order')->insertGetId($data);
            $this->mysicLog->info($dealer_id, '分销订单表dealer_order表加数据结果');


        }

        // 订单是否已完成
        if ($order['order_status']['value'] != 30) {
            $this->mysicLog->info($order['order_status']['value'], '订单状态为未完成，不满足分销条件');
            return false;
        }

        // 订单支付方式
        if ($order['pay_type']['value'] != 20) {
            return false;
        }

        // 分销订单详情
        $dealerOrder = Db::name('dealer_order')->where(['order_id'=>$order['order_id'],'is_settled'=>0,'order_type'=>$order_type])->find();

        if(!$dealerOrder){
            $this->mysicLog->info('', '无分销订单');
            return false;
        }
        $this->mysicLog->info($dealerOrder, '普通分销订单佣金分销订单详情');

        // +----------------------------------------------------------------------
        // | dealer_order表更新数据----分销商订单记录表
        // +----------------------------------------------------------------------
        Db::name('dealer_order')
            ->where(['order_id'=>$order['order_id'],'order_type'=>$order_type])
            ->update(['is_settled' => 1,'settle_time' => time()]);

        $this->mysicLog->info($dealerOrder['first_money'], '分销商用户记录表dealer_user，分销佣金');
        $this->mysicLog->info($dealerOrder['first_user_id'], '分销商用户记录表dealer_user，上级id');

        if($dealerOrder['first_user_id']>0 && $dealerOrder['first_money']>0){
            // +----------------------------------------------------------------------
            // | dealer_user表更新数据----分销商用户记录表
            // +----------------------------------------------------------------------
            Db::name('dealer_user')
                ->where(['user_id'=>$dealerOrder['first_user_id']])
                ->setInc('money', $dealerOrder['first_money']);


            // +----------------------------------------------------------------------
            // | dealer_capital表加数据----分销商资金明细表
            // +----------------------------------------------------------------------
            $capitalData = [
                'user_id'=>$dealerOrder['first_user_id'],
                'flow_type'=>$flow_type,
                'money'=>$dealerOrder['first_money'],
                'wxapp_id'=>$dealerOrder['wxapp_id'],
                'create_time'=>time(),
                'update_time'=>time(),
            ];

            $this->mysicLog->info($capitalData, '分销商资金明细表数据');
            $dealer_capital_id = Db::name('dealer_capital')->insertGetId($capitalData);

            $this->mysicLog->info($dealer_capital_id, '获取分销商资金明细表ID');
        }

    }


    /**
     * 计算商品的订单分销佣金方案一
     * @param $order
     * @return array
     */
    private function getCapitalOne($order)
    {

        // 分销层级
        $level = 1;
        // 分销订单佣金数据
        $capital = [
            // 订单总金额(不含运费)
            'orderPrice' => bcsub($order['pay_price'], $order['express_price'], 2),
            // 一级分销佣金
            'first_money' => 0.00,
            // 二级分销佣金
            'second_money' => 0.00,
            // 三级分销佣金
            'third_money' => 0.00
        ];

        // 计算分销佣金
        foreach ($order['goods'] as $goods) {

            // 商品实付款金额
            $goodsPrice = min($capital['orderPrice'], $goods['total_pay_price']);

            // 计算商品实际佣金
            $goodsCapital = $this->calculateGoodsCapital($goods, $goodsPrice);
            // 累积分销佣金
            $level >= 1 && $capital['first_money'] += $goodsCapital['first_money'];
            $level >= 2 && $capital['second_money'] += $goodsCapital['second_money'];
            $level == 3 && $capital['third_money'] += $goodsCapital['third_money'];
        }

        return $capital;
    }


    /**
     * 计算商品实际佣金
     * @param $setting
     * @param $goods
     * @param $goodsPrice
     * @return array
     */
    private function calculateGoodsCapital($goods, $goodsPrice)
    {

        // 商品单独分销
        if ($goods['dealer_money_type'] == 10) {
            // 分销佣金类型：百分比
            return [
                'first_money' => $goodsPrice * ($goods['first_money'] * 0.01),
                'second_money' => $goodsPrice * ($goods['second_money'] * 0.01),
                'third_money' => $goodsPrice * ($goods['third_money'] * 0.01)
            ];
        } else {
            return [
                'first_money' => $goods['total_num'] * $goods['first_money'],
                'second_money' => $goods['total_num'] * $goods['second_money'],
                'third_money' => $goods['total_num'] * $goods['third_money']
            ];
        }
    }



    //当面付创建分销订单
    public function createFaceOrder($order,$consume_charge,$upUserId,$wxapp_id,$order_type,$flow_type,$dealer_case){

        $this->mysicLog->info("开始", '当面付创建分销订单');
        $this->mysicLog->info($consume_charge, '分销比例');
        $this->mysicLog->info($upUserId, '上级id');

        $first_money = bcmul($consume_charge/100, $order['pay_price'],2);
        $this->mysicLog->info($first_money, '分销金额');

        // +----------------------------------------------------------------------
        // | dealer_order表加数据----分销商订单记录表
        // +----------------------------------------------------------------------

        if($first_money>0){
            $data = [
                'user_id' => $order['user_id'],//用户id (买家)
                'order_id' => $order['order_id'],//订单id
                'order_type' => $order_type,//订单类型(10商城订单 20拼团订单 30 购买vip 40 购买爆品礼 50 当面付 60分红转化)
                'order_price' => $order['pay_price'],//订单支付金额
                'first_user_id' => $upUserId,//分销商用户id(一级)
                'second_user_id' => 0,//分销商用户id(二级)
                'third_user_id' => 0,//分销商用户id(三级)
                'first_money' => $first_money,//分销佣金(一级)
                'second_money' => 0,//分销佣金(二级)
                'third_money' => 0,//分销佣金(三级)
                'is_invalid' => 0,//订单是否失效(0未失效 1已失效)
                'is_settled' => 1,//是否已结算佣金(0未结算 1已结算)
                'settle_time' => time(),//结算时间
                'wxapp_id' => $wxapp_id,//小程序id
                'create_time' => time(),//创建时间
                'update_time' => time(),//更新时间
                'dealer_case' => $dealer_case,//分销方案
            ];

            $this->mysicLog->info($data, '分销订单表dealer_order表加数据');
            $dealer_id = Db::name('dealer_order')->insertGetId($data);
            $this->mysicLog->info($dealer_id, '分销订单表dealer_order表加数据结果');

            if($dealer_id){
                // +----------------------------------------------------------------------
                // | dealer_user表更新数据----分销商用户记录表
                // +----------------------------------------------------------------------
                Db::name('dealer_user')->where(['user_id'=>$upUserId])->setInc('money', $first_money);
                // +----------------------------------------------------------------------
                // | dealer_capital表加数据----分销商资金明细表
                // +----------------------------------------------------------------------
                $capitalData = [
                    'user_id'=>$upUserId,
                    'flow_type'=>$flow_type,
                    'money'=>$first_money,
                    'wxapp_id'=>$wxapp_id,
                    'create_time'=>time(),
                    'update_time'=>time(),
                ];

                $this->mysicLog->info($capitalData, '分销商资金明细表数据');
                $dealer_capital_id = Db::name('dealer_capital')->insertGetId($capitalData);
                $this->mysicLog->info($dealer_capital_id, '分销商资金明细表ID');

            }

        }

    }




    /**
     * 更新订单记录
     * @param $payType
     * @param $payData
     * @return false|int
     * @throws \Exception
     */
    private function updateOrderInfo($payType, $order,$payData)
    {

        // 更新商品库存、销量
        StockFactory::getFactory($this->model['order_source'])->updateStockSales($this->model['goods']);

        $time = time();
        // 整理订单信息
        $upData =[
            'pay_type' => $payType,//支付方式
            'pay_status' => 20,//付款状态(10未付款 20已付款)
            'pay_time' => $time//付款时间
        ];

        //虚拟商品
        if($order['is_fictitious']==1){
            $upData['order_status'] = 30;//订单状态(10进行中 20取消 21待取消 30已完成)
            $upData['delivery_status'] = 20;//发货状态(10未发货 20已发货)
            $upData['delivery_time'] = $time;//发货时间
            $upData['receipt_status'] = 20; //收货状态(10未收货 20已收货)
            $upData['receipt_time'] = $time;//收货时间
            //$upData['delivery_type'] = 20;//配送方式(10快递配送 20上门自提)
            $upData['is_settled'] = 1;//订单是否已结算(0未结算 1已结算)
        }

        $upData['transaction_id'] = $payData['transaction_id'] ?? '';
        // 更新订单状态
        return $this->model->isUpdate(true)->save($upData);
    }


    private function updateFaceOrderInfo($payType, $payData)
    {
        $time = time();
        // 整理订单信息
        $order =[
            'pay_type'       => $payType,//支付方式
            'pay_status'     => 20,//付款状态(10未付款 20已付款)
            'pay_time'       => $time,//付款时间
            'order_status'   => 30,//订单状态(10进行中 20取消 21待取消 30已完成)
            'delivery_status' => 20,//发货状态(10未发货 20已发货)
            'delivery_time'   => $time,//发货时间
            'receipt_status'  =>20,//收货状态(10未收货 20已收货)
            'receipt_time'  =>$time,//收货时间
            'delivery_type'  =>30,//配送方式(10快递配送 20上门自提 30当面付)
            'is_settled'  =>1,//订单是否已结算(0未结算 1已结算)
        ];
        // $this->log('更新订单状态 - 回调transaction', $payData['transaction_id']);
        $this->log('更新订单状态 - payType', $payType);
        $order['transaction_id'] = $payData['transaction_id'] ?? '';
        $this->log('更新订单状态 - order', $order);

        // 更新订单状态
        return $this->model->isUpdate(true)->save($order);
    }




    /**
     * 记录订单支付信息
     * @param $payType
     * @throws \think\Exception
     */
    private function updatePayInfo($payType)
    {

        // 余额支付
        if ($payType == PayTypeEnum::BALANCE) {
            // 更新用户余额
            $this->mysicLog->info('','余额支付 - 开始减扣用户余额...');
            $result = $this->user->setDec('money', $this->model['pay_price']);
            $this->mysicLog->info($result,'减扣用户余额结果');
            MoneyLogModel::add([
                'scene'=>Scene::CONSUME,
                'user_id' => $this->user['user_id'],
                'money' => -$this->model['pay_price'],
                'order_no' => $this->model['order_no'],
            ]);
            $this->mysicLog->info([
                '余额变动场景(10用户购买会员卡充值 20退款 30用户消费 40管理员操作)'=>Scene::CONSUME,
                '用户ID' => $this->user['user_id'],
                '减扣金额' => $this->model['pay_price'],
                '订单号' => $this->model['order_no'],
            ],'余额减扣计入用户余额消费流水');
        }
        // 微信支付
        if ($payType == PayTypeEnum::WECHAT) {
            // 更新prepay_id记录
//            WxappPrepayIdModel::updatePayStatus($this->model['order_id'], OrderTypeEnum::MASTER);
            $this->mysicLog->info('微信支付1');
            //如果是微信支付，且支付的时候选择了零钱抵扣，扣除用户零钱
            $this->mysicLog->info(gettype($this->model['balance_money']),$this->model['balance_money']);
            if (!isset($this->model['balance_money']) || !isset($this->model['balance_num']) || $this->model['balance_money']*$this->model['balance_num']>0){
                $this->mysicLog->info('微信支付1：使用了零钱');
                $this->user->setDec('balance', $this->model['balance_money']);
                // 用户余额变动明细
                BalanceLog::add(20, [
                    'user_id'  =>$this->user['user_id'],
                    'money'    =>-$this->model['balance_money'],
                    'wxapp_id' =>$this->model['wxapp_id'],
                ], ['order_no' =>$this->model['order_no']]);
            }
            $this->mysicLog->info('微信支付2');
            //如果微信支付，且支付的时候使用了积分，扣除用户积分
            $this->mysicLog->info(gettype($this->model['points_money']),$this->model['points_money']);
            if (!isset($this->model['points_money']) || $this->model['points_num']!==0){
                $this->mysicLog->info('微信支付2:使用了积分');
                $this->user->setDec('points', $this->model['points_money']);
                $this->mysicLog->info('微信支付后，减去用户积分');
                PointsLogModel::add([
                    'wxapp_id' =>$this->model['wxapp_id'],
                    'user_id' =>$this->user['user_id'],
                    'value' => $this->model['points_money'],
                    'describe' =>'积分抵扣',
                ]);
            }
            $this->mysicLog->info('微信支付3');
            $this->mysicLog->info($this->model['coupon_id'],'优惠券id：');
            //如果支付的时候使用了优惠券，扣除优惠券
            $this->mysicLog->info(gettype($this->model['coupon_id']),$this->model['coupon_id']);
            if (!isset($this->model['coupon_id']) || $this->model['coupon_id']!==0){
                $this->mysicLog->info($this->model['coupon_id'],'优惠券');
                $this->mysicLog->info($this->model,'微信支付使用优惠券订单模型内容');
                $reault=db('user_coupon')->where(['user_coupon_id'=>$this->model['coupon_id'],'wxapp_id'=>$this->model['wxapp_id']])->setField('is_use',1);
                $this->mysicLog->info($reault,'更新微信支付使用优惠券使用结过');
            }
        }
    }
}